'''
Copyright <2020> Alejandro "alkeon" Castilla <alkeon@autistici.org>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import requests
import sys

links = []
search_url = ""
avoid_get_download_link = False
selection_flag = ""

def term_options():
	selection_flag = ""
	avoid_get_download_link = False
	list_videos = False
	if(len(sys.argv) == 3):

			if(sys.argv[1] == "-c"):
				search_url = sys.argv[2]
				selection_flag = "-c"
				avoid_get_download_link = True
			elif(sys.argv[1] == "-u"):
				search_url = sys.argv[2]
				selection_flag = "-u"
				avoid_get_download_link = True
			elif(sys.argv[1] == "-l"):
				search_url = sys.argv[2]
				list_videos = True
	else:
		search_url = sys.argv[1]
	
	return search_url, selection_flag, avoid_get_download_link, list_videos

def print_array():
	i = 0
	while(i < len(links)):
		print(str(i) + ".- " + links[i])
		i += 1

def get_link(line):
	first_quote = line.find("\"")
	second_quote = line.find("\"", first_quote + 1)
	url = line[first_quote + 1:second_quote]
	if(url not in links and url.find("#comments") == -1 and url.find("?autoplay=true") == -1):
		links.append(url)

def search(search, selection_flag):
	base_url_programs = "https://www.ivoox.com/SEARCH_sw_1_1.html"
	base_url_users = "https://www.ivoox.com/SEARCH_sw_5_1.html"
	base_url_selected = "https://www.ivoox.com/SEARCH_sb.html"

	if(selection_flag == "-c"):
		base_url_selected = base_url_programs
	elif(selection_flag == "-u"):
		base_url_selected = base_url_users

	search = search.replace(" ", "-")
	url_search = base_url_selected.replace("SEARCH", search)

	p = requests.get(url_search)
	lines = p.text.splitlines()
	for line in lines:
		if(line.find("href=\"") != -1):
			if(line.find("audios-mp3") != -1):
				get_link(line)
			elif(line.find("_sq_") != -1):
				get_link(line)
			elif(line.find("_aj_") != -1):
				get_link(line)

def get_download_link(url):
	base_url_download = "http://www.ivoox.com/listen_mn_ID_1.mp3?internal=HTML5"
	first_quote = url.find("_rf_")
	second_quote = url.find("_", first_quote + 5)
	id_url = url[first_quote + 4:second_quote]
	print(id_url)
	url_download = base_url_download.replace("ID", id_url)
	p = requests.get(url_download)
	print(p.url)

def list_videos_from_channel(search_url):
	p = requests.get(search_url)
	lines = p.text.splitlines()
	for line in lines:
		if(line.find("href=\"") != -1):
			if(line.find("escuchar-audios") != -1):
				get_link(line)
	p = requests.get(links[0])
	lines = p.text.splitlines()
	for line in lines:
		if(line.find("href=\"") != -1):
			if(line.find("audios-mp3") != -1):
				get_link(line)

if(sys.argv[1] == '-h' or sys.argv[1] == '--help'):
	print(" cliox \"keyword\" | Allows searching audios");
	print(" cliox -c \"channel\" | Allows searching channels ");
	print(" cliox -u \"user\" | Allows searching users ");
	print(" cliox -l \"channel/user url\" | Allows listing all videos from channel or user ");
	print(" cliox -h | Show help ");
else:
	search_url, selection_flag, avoid_get_download_link, list_videos = term_options()
	print(search_url)

	if(not list_videos):

		search(search_url, selection_flag)
		print_array()

		if(not avoid_get_download_link):
			i = input("Choose a link\n")
			if(i != -1):
				get_download_link(links[int(i)])
	else:
		list_videos_from_channel(search_url)
		print_array()
		if(not avoid_get_download_link):
			i = input("Choose a link\n")
			if(i != -1):
				get_download_link(links[int(i)])
